let express = require('express');
let router = express.Router();
var multer = require('../../components/multerUtil');
let filter = require('../../components/filter');

/**
 * 查询农户数据 by p 2018-06-11
 *
 * 按条件查询农户数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;
    let user = req.session.user;

    var limits = "";
    var sql = "";
    var datas = [];

    sql = " where departmentId like '" + user.departmentId + "%'";
    if (params.state !== undefined && params.state !== "") {
        sql += " and state = ?";
        datas.push(params.state);
    }

    req.app.db.query("select count(1) as totalCount from info " + sql, datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results[0].totalCount === 0) {
            res.json({"success": true, "data": {}, "totalCount": 0});
            return;
        }

        let totalCount = results[0].totalCount;

        if (params.pageNo > 0 && params.pageSize > 0) {
            limits = " limit ?, ?";
            datas.push((params.pageNo - 1) * params.pageSize);
            datas.push(params.pageSize * 1);
        }

        req.app.db.query("select * from info " + limits, datas, function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "data": results, "totalCount": totalCount, "message": ""});
        });
    });
});

/**
 * 查看农户数据 by p 2018-06-11
 *
 * 按id查看指定的农户信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    req.app.db.query("select * from info where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": global.noDataErr});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

/**
 * 修改农户数据 by p 2018-06-11
 *
 *
 */
router.put('/:id', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;

    req.app.db.query("call proc_info_maintain(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        [params.id, params.planYear, params.departmentId, user.id, user.trueName, params.sonDepartmentId, params.sonDepartmentName, params.personGroup,
            params.personId, params.personName, params.personSex, params.personImage, params.personNation, params.personAddr, params.personNum, params.personTel,
            params.houseAge, params.houseOldType, params.houseOldSize, params.houseNewSize, params.toiletType, params.toiletTypeName,
            params.buildMode, params.buildModeName, params.rebuildMode, params.rebuildModeName, params.buildCompany,
            params.rebuildBeginDate, params.rebuildEndDate, params.acceptanceDate, params.acceptanceImage1, params.acceptanceImage2, params.acceptanceImage3,
            params.fundSendDate, params.fundSendImage, params.isAcceptance, params.grantType, params.grantTypeName,
            params.sumFund, params.provinceFund, params.countiesFund, params.selfFund,
            params.houseOldImage, params.houseBuildingImage, params.houseOutNewImage, params.houseInNewImage,
            params.delegaterImage, params.fillUserName, params.fillUserTel, params.fillUserUnit], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            let result = results[0][0]._result;

            res.json({"success": result === 1, "message": global.infoMsg.update[result]});
        });

});

/**
 * 新增农户数据 by p 2018-06-11
 *
 *
 */
router.post('/', filter.authorize, multer.fields([
    {name: 'personImageU', maxCount: 1},
    {name: 'acceptanceImage1U', maxCount: 1},
    {name: 'acceptanceImage2U', maxCount: 1},
    {name: 'acceptanceImage3U', maxCount: 1},
    {name: 'fundSendImageU', maxCount: 1},
    {name: 'houseOldImageU', maxCount: 1},
    {name: 'houseBuildingImageU', maxCount: 1},
    {name: 'houseOutNewImageU', maxCount: 1},
    {name: 'houseInNewImageU', maxCount: 1},
    {name: 'delegaterImageU', maxCount: 1}
]), function (req, res, next) {
    let params = req.body;
    let user = req.session.user;
    let houseOldSize = 0, houseNewSize = 0, toiletType = 0, buildMode = 0, rebuildMode = 0, isAcceptance = 0;
    let sumFund = 0, provinceFund = 0, countiesFund = 0, selfFund = 0;
    let rebuildBeginDate = "", rebuildEndDate = "", acceptanceDate = "", fundSendDate = "";
    let personImage = "", acceptanceImage1 = "", acceptanceImage2 = "", acceptanceImage3 = "", fundSendImage = "";
    let houseOldImage = "", houseBuildingImage = "", houseOutNewImage = "", houseInNewImage = "", delegaterImage = "";

    if (params.houseOldSize !== undefined && params.houseOldSize !== "" && params.houseOldSize > 0) {
        houseOldSize = params.houseOldSize;
    }

    if (params.houseNewSize !== undefined && params.houseNewSize !== "" && params.houseNewSize > 0) {
        houseNewSize = params.houseNewSize;
    }

    if (params.sumFund !== undefined && params.sumFund !== "" && params.sumFund > 0) {
        sumFund = params.sumFund;
    }

    if (params.provinceFund !== undefined && params.provinceFund !== "" && params.provinceFund > 0) {
        provinceFund = params.provinceFund;
    }

    if (params.countiesFund !== undefined && params.countiesFund !== "" && params.countiesFund > 0) {
        countiesFund = params.countiesFund;
    }

    if (params.selfFund !== undefined && params.selfFund !== "" && params.selfFund > 0) {
        selfFund = params.selfFund;
    }

    if (params.rebuildBeginDate !== undefined && params.rebuildBeginDate !== "") {
        rebuildBeginDate = params.rebuildBeginDate;
    }

    if (params.rebuildEndDate !== undefined && params.rebuildEndDate !== "") {
        rebuildEndDate = params.rebuildEndDate;
    }

    if (params.acceptanceDate !== undefined && params.acceptanceDate !== "") {
        acceptanceDate = params.acceptanceDate;
    }

    if (params.fundSendDate !== undefined && params.fundSendDate !== "") {
        fundSendDate = params.fundSendDate;
    }

    if (params.toiletType !== undefined && params.toiletType !== "") {
        toiletType = params.toiletType;
    }

    if (params.buildMode !== undefined && params.buildMode !== "") {
        buildMode = params.buildMode;
    }

    if (params.rebuildMode !== undefined && params.rebuildMode !== "") {
        rebuildMode = params.rebuildMode;
    }

    if (params.isAcceptance !== undefined && params.isAcceptance !== "") {
        isAcceptance = params.isAcceptance;
    }

    if (params.planYear === undefined || params.planYear === "") {
        res.json({"success": false, "message": "计划年度不能为空！"});
        return;
    }

    if (params.sonDepartmentId === undefined || params.sonDepartmentId === "") {
        res.json({"success": false, "message": "请选择村！"});
        return;
    }

    if (params.personGroup === undefined || params.personGroup === "") {
        res.json({"success": false, "message": "村民小组不能为空！"});
        return;
    }

    if (params.personId === undefined || params.personId === "") {
        res.json({"success": false, "message": "农户身份证号不能为空！"});
        return;
    }

    if (params.personSex === undefined || params.personSex === "") {
        res.json({"success": false, "message": "请选择农户性别！"});
        return;
    }

    if (req.files["personImageU"] !== undefined) {
        personImage = req.files["personImageU"][0].path;
    }
    else {
        res.json({"success": false, "message": "必须上传农户手持身份证照片！"});
        return;
    }

    if (params.personNation === undefined || params.personNation === "") {
        res.json({"success": false, "message": "农户民族不能为空！"});
        return;
    }

    if (params.personAddr === undefined || params.personAddr === "") {
        res.json({"success": false, "message": "改厕房屋地址不能为空！"});
        return;
    }

    if (params.personNum === undefined || params.personNum === "") {
        res.json({"success": false, "message": "家庭人数不能为空！"});
        return;
    }

    if (params.personTel === undefined || params.personTel === "") {
        res.json({"success": false, "message": "联系电话不能为空！"});
        return;
    }

    if (req.files["acceptanceImage1U"] !== undefined) {
        acceptanceImage1 = req.files["acceptanceImage1U"][0].path;
    }
    if (req.files["acceptanceImage2U"] !== undefined) {
        acceptanceImage2 = req.files["acceptanceImage2U"][0].path;
    }
    if (req.files["acceptanceImage3U"] !== undefined) {
        acceptanceImage3 = req.files["acceptanceImage3U"][0].path;
    }
    if (req.files["fundSendImageU"] !== undefined) {
        fundSendImage = req.files["fundSendImageU"][0].path;
    }
    if (req.files["houseOldImageU"] !== undefined) {
        houseOldImage = req.files["houseOldImageU"][0].path;
    }
    if (req.files["houseBuildingImageU"] !== undefined) {
        houseBuildingImage = req.files["houseBuildingImageU"][0].path;
    }
    if (req.files["houseOutNewImageU"] !== undefined) {
        houseOutNewImage = req.files["houseOutNewImageU"][0].path;
    }
    if (req.files["houseInNewImageU"] !== undefined) {
        houseInNewImage = req.files["houseInNewImageU"][0].path;
    }
    if (req.files["delegaterImageU"] !== undefined) {
        delegaterImage = req.files["delegaterImageU"][0].path;
    }

    req.app.db.query("call proc_info_maintain(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        [0, params.planYear, user.id, params.sonDepartmentId, params.personGroup,
            params.personId, params.personName, params.personSex, personImage, params.personNation, params.personAddr, params.personNum, params.personTel,
            params.houseAge, params.houseOldType, houseOldSize, houseNewSize, toiletType,
            buildMode, rebuildMode, params.buildCompany,
            rebuildBeginDate, rebuildEndDate, acceptanceDate, acceptanceImage1, acceptanceImage2, acceptanceImage3,
            fundSendDate, fundSendImage, isAcceptance, params.grantType,
            sumFund, provinceFund, countiesFund, selfFund,
            houseOldImage, houseBuildingImage, houseOutNewImage, houseInNewImage,
            delegaterImage, params.fillUserName, params.fillUserTel, params.fillUserUnit], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            let result = results[0][0]._result;

            res.json({"success": result === 1, "message": global.infoMsg.add[result]});
        });
});

/**
 * 提交审核农户数据 by p 2018-09-01
 *
 *
 */
router.post('/:id/submit', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;

    req.app.db.query("call proc_info_submit(?, ?)", [params.id, user.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        let result = results[0][0]._result;

        res.json({"success": result === 1, "message": global.infoMsg.submit[result]});
    });
});

/**
 * 审核农户数据 by p 2018-09-01
 *
 *
 */
router.post('/:id/audit', filter.authorize, function (req, res, next) {
    let params = req.body;
    let user = req.session.user;

    req.app.db.query("call proc_info_audit(?, ?, ?, ?)", [params.id, user.id, params.state, params.content], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        let result = results[0][0]._result;

        res.json({"success": result === 1, "message": global.infoMsg.audit[result]});
    });
});

/**
 * 删除农户信息 by v 2018-06-11
 *
 * 按id删除指定的农户信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let user = req.session.user;

    req.app.db.query("call proc_info_delete(?, ?)", [params.id, user.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        let result = results[0][0]._result;

        res.json({"success": result === 1, "message": global.infoMsg.delete[result]});
    });
});

module.exports = router;